<template>
  <div class="search-suggestion">
    <template v-if="suggestionList[0]">
      <van-cell
        icon="search"
        v-for="(item, index) in suggestionList"
        :key="index"
        @click="$emit('search', item)"
      >
        <template #title>
          <!-- v-html渲染搜索的高亮 ,不要动原始的数据-->
          <div v-html="lightResult(item)"></div>
        </template>
      </van-cell>
    </template>
    <template v-else>
      <van-cell title="暂无数据" class="none"></van-cell>
    </template>
  </div>
</template>

<script>
import { getSuggestionAPI } from "@/api/login";
//文档上是comonJs的引入规范，以下是解构出来的的
import { debounce } from "lodash";
export default {
  name: "SearchSuggestion",
  components: {},
  props: ["searchText"],
  data() {
    return {
      suggestionList: [],
    };
  },
  computed: {},
  watch: {
    searchText: {
      immediate: true,
      handler: debounce(function (newVal) {
        if (!/[\\]/.test(newVal)) {
          this.getSuggestionFn(newVal);
        }
      }, 150),
      //防抖--使用lodash
    },
  },
  created() {},
  mounted() {},
  methods: {
    async getSuggestionFn(val) {
      let re = await getSuggestionAPI(val);
      let {
        data: {
          data: { options },
        },
      } = re;
      console.log(options);
      // 请求回来的数据有时候是空，或者null
      this.suggestionList = options;
    },
    lightResult(item) {
      //自己再思考一种方法
      let str = `<span style="color: red">${this.searchText}</span>`;
      // 全局匹配--重点看这个new RegExp
      const reg = new RegExp(this.searchText, "ig");
      return item.replace(reg, str);
    },
  },
};
</script>

<style scoped lang="less">
.search-suggestion {
  .none {
    text-align: center;
  }
}
</style>
